package com.weetop.akly.activity.work;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.weetop.akly.R;
import com.weetop.akly.activity.communicationIndex.IndexActivity;
import com.weetop.akly.adapter.FullyGridLayoutManager;
import com.weetop.akly.adapter.MyGridImageAdapter;
import com.weetop.akly.adapter.MyGridSpryAdapter;
import com.weetop.akly.base.BaseActivity;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.bean.AccountInfoBean;
import com.weetop.akly.bean.ApproveFromKeyBean;
import com.weetop.akly.bean.MemberBean;
import com.weetop.akly.presenter.WorkApplyPresent;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.view.WorkApplyView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SignOutActivity extends BaseActivity<WorkApplyPresent> implements WorkApplyView {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_data_title)
    TextView tvDataTitle;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_outsign_date)
    TextView tvOutsignDate;
    @BindView(R.id.rl_outsign_date)
    RelativeLayout rlOutsignDate;
    @BindView(R.id.tv_outsign_time)
    TextView tvOutsignTime;
    @BindView(R.id.rl_outsign_time)
    RelativeLayout rlOutsignTime;
    @BindView(R.id.et_reason)
    EditText etReason;
    @BindView(R.id.rv_shenpirenyuan)
    RecyclerView rvShenpirenyuan;
    @BindView(R.id.bt_submit)
    QMUIButton btSubmit;
    private MyGridImageAdapter adapter;
    private MyGridSpryAdapter spAdapter;
    private AccountInfoBean.InfoBean info;
    private AccountInfoBean.AccountBean accountInfo;
    private TimePickerView pvDate, pvTime;
    private ArrayList<ApproveFromKeyBean> approveKeys;
    private String signTime;
    private String signDate;
    private String kaoqinId, status;

    @Override
    protected WorkApplyPresent createPresenter() {
        return new WorkApplyPresent(this, this);
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private ArrayList<MemberBean> selectSpryList = new ArrayList<>();
    private String modelId = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_out_sign);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        kaoqinId = intent.getStringExtra("kaoqin_id");
        status = intent.getStringExtra("status");

        setTitleInfo("补卡申请");
        initDatePicker();
        initTimePicker();
        mPresenter.getApproveFormKeyList(modelId);

        initFuJianRv();
        initShenpirenRv();
        initUserInfo();
    }

    private void initFuJianRv() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
//        adapter = new MyGridImageAdapter(mActivity, onAddPicClickListener);
        adapter = new MyGridImageAdapter(mActivity, onAddPicClickListener, true);
        adapter.setList(selectList);
        adapter.setSelectMax(4);
        recyclerView.setAdapter(adapter);
    }

    private void initShenpirenRv() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 1, GridLayoutManager.HORIZONTAL, false);
        rvShenpirenyuan.setLayoutManager(manager);
        spAdapter = new MyGridSpryAdapter(mActivity, onAddSpryClickListener, true);
        spAdapter.setList(selectSpryList);
        rvShenpirenyuan.setAdapter(spAdapter);
    }

    private void initUserInfo() {
        AccountInfoBean accountInfoBean = myApplication.getAccountInfoBean();
        info = accountInfoBean.getInfo();
        accountInfo = accountInfoBean.getAccount();
        tvName.setText(info.getName());
        tvDepartment.setText(info.getDepartment());
        tvJob.setText(info.getJob());
        tvAccount.setText(accountInfo.getAccount());
    }

    private MyGridImageAdapter.onAddPicClickListener onAddPicClickListener = new MyGridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(mActivity)
                    .openGallery(PictureMimeType.ofImage())
                    .maxSelectNum(4 - selectList.size())
                    .compress(true)// 是否压缩 true or false
                    .enableCrop(false)
                    .minimumCompressSize(350)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };

    private MyGridSpryAdapter.onAddSpryClickListener onAddSpryClickListener = new MyGridSpryAdapter.onAddSpryClickListener() {
        @Override
        public void onAddSpryClick() {
            if (selectSpryList.size() > 0) {
                ToastUtils.showShort("最多只能选择一个审批人!");
                return;
            }
            Intent intent = new Intent();
            intent.putExtra("mode_id", modelId);
            BaseUtils.toActivity(mActivity, IndexActivity.class, intent);
        }
    };


    private void initDatePicker() {//Dialog 模式下，在底部弹出
        pvDate = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                ToastUtils.showShort(getTime(date, true));
                signDate = getTime(date, true);
                tvOutsignDate.setText(signDate);
                Log.i("pvTime", "onTimeSelect");

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvDate.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvDate.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private ArrayList<String> state = new ArrayList<>();
    private String selectState = "";
    private QMUIBottomSheet chooseGroupSheet;

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        //初始化考勤组弹窗
        state.add("全天");
        state.add("上班卡");
        state.add("下班卡");
        QMUIBottomSheet.BottomListSheetBuilder chooseHeadImgBottomSheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(this);
        for (String datum : state) {
            chooseHeadImgBottomSheetBuilder.addItem(datum);
        }
        chooseHeadImgBottomSheetBuilder.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
            selectState = state.get(position);
            tvOutsignTime.setText(selectState);
            dialog.dismiss();
        });
        chooseGroupSheet = chooseHeadImgBottomSheetBuilder.build();
//        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
//            @Override
//            public void onTimeSelect(Date date, View v) {
////                ToastUtils.showShort(getTime(date, false));
//                signTime = getTime(date, false) + ":00";
//                tvOutsignTime.setText(signTime);
//                Log.i("pvTime", "onTimeSelect");
//
//            }
//        })
//                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
//                    @Override
//                    public void onTimeSelectChanged(Date date) {
//                        Log.i("pvTime", "onTimeSelectChanged");
//                    }
//                })
//                .setType(new boolean[]{false, false, false, true, true, false})
//                .setLabel("", "", "", "", "", "")
//                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
//                .addOnCancelClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Log.i("pvTime", "onCancelClickListener");
//                    }
//                })
//                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
//                .setLineSpacingMultiplier(2.0f)
//                .isAlphaGradient(true)
//                .build();

//        Dialog mDialog = pvTime.getDialog();
//        if (mDialog != null) {
//
//            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
//                    ViewGroup.LayoutParams.MATCH_PARENT,
//                    ViewGroup.LayoutParams.WRAP_CONTENT,
//                    Gravity.BOTTOM);
//
//            params.leftMargin = 0;
//            params.rightMargin = 0;
//            pvTime.getDialogContainerLayout().setLayoutParams(params);
//
//            Window dialogWindow = mDialog.getWindow();
//            if (dialogWindow != null) {
//                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
//                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
//                dialogWindow.setDimAmount(0.3f);
//            }
//        }
    }

    private String getTime(Date date, boolean isDate) {//可根据需要自行截取数据显示
        Log.d("getTime()", "yyyy-MM-dd HH:mm:ss  choice date millis: " + date.getTime());
        String pattern = isDate ? "yyyy-MM-dd" : "HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    @Override
    public void getApproveFormKeySuccess(BaseModel<ArrayList<ApproveFromKeyBean>> o) {
        approveKeys = o.getData();
    }

    @Override
    public void submitSuccess(BaseModel<Object> o) {
        ToastUtils.showShort("提交成功");
        finish();
    }

    @Override
    public void uploadSucess(String filePaths) {
        String leaderIds = "";
        for (MemberBean leader : selectSpryList) {
            if (TextUtils.isEmpty(leaderIds)) {
                leaderIds = leader.getId() + "";
            } else {
                leaderIds = leaderIds + "," + leader.getId() + "";
            }
        }
        HashMap<String, String> form = new HashMap<>();
        for (int i = 0; i < approveKeys.size(); i++) {
            ApproveFromKeyBean formKey = approveKeys.get(i);
            form.put("form[" + i + "][form_id]", formKey.getForm_id() + "");
            if ("原因".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", etReason.getText().toString().trim());
            } else if ("操作考勤".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", kaoqinId);
            } else if ("状态".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", status);
            } else if ("补卡日期".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", signDate);
            } else if ("补卡时间".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", signTime);
            } else if ("附件".equals(formKey.getForm_key())) {
                form.put("form[" + i + "][form_val]", filePaths);
            }
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("make_day", signDate);
        params.put("make_type", (state.indexOf(selectState) + 1) + "");
        params.put("leave_reason", etReason.getText().toString().trim());
        params.put("approve_user_id", leaderIds);
        mPresenter.cardAdd(params);
    }

    @OnClick({R.id.rl_outsign_date, R.id.rl_outsign_time, R.id.bt_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_outsign_date:
                pvDate.show(view);
                break;
            case R.id.rl_outsign_time:
                chooseGroupSheet.show();
//                pvTime.show(view);
                break;
            case R.id.bt_submit:
                String reason = etReason.getText().toString().trim();
//                if (TextUtils.isEmpty(status) || TextUtils.isEmpty(kaoqinId)) {
//                    ToastUtils.showShort("未传入考勤状态");
//                    return;
//                } else
                if (TextUtils.isEmpty(signDate)) {
                    ToastUtils.showShort("请选择补卡日期");
                    return;
                } else if (TextUtils.isEmpty(selectState)) {
                    ToastUtils.showShort("请选择补卡时间");
                    return;
                } else if (TextUtils.isEmpty(reason)) {
                    ToastUtils.showShort("请填写原因");
                    return;
                } else if (selectSpryList.size() <= 0) {
                    ToastUtils.showShort("请添加审批人员");
                    return;
                }
                mPresenter.uploadFiles(selectList);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> datapic = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(datapic);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String select_members = intent.getStringExtra("select_members");
        if (!TextUtils.isEmpty(select_members)) {
            ArrayList<MemberBean> selectMembers = GsonUtils.fromJson(select_members, GsonUtils.getListType(MemberBean.class));
            selectSpryList.addAll(selectMembers);
            spAdapter.setList(selectSpryList);
            spAdapter.notifyDataSetChanged();
        }
    }
}
